from django.db.models import Q
from rest_framework import viewsets, mixins
from rest_framework.response import Response
from rest_framework.views import APIView
from django_filters.rest_framework import DjangoFilterBackend

from .backend import JwtQueryParamsAuthentication
from Apps.Profile.utils.jwt_auth import create_token
from .filter import UserFilter
from .models import *
from .serializers import *
from .pagination import UsersPagination


class LoginView(APIView):
    def post(self, request, *args, **kwargs):
        username = request.data.get('username')
        pwd = request.data.get('password')
        user_object = User.objects.get(Q(username=username) | Q(mobile=username) | Q(email=username))

        if not user_object.check_password(pwd):
            return Response({'code': 1000, 'error': '用户名或密码错误'})

        token = create_token({'id': user_object.id, 'name': user_object.username})
        return Response({'code': 1001, 'token': token})


class UserViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
    queryset = User.objects.all().order_by('id')
    serializer_class = UserSerializer
    pagination_class = UsersPagination
    filter_backends = (DjangoFilterBackend,)
    # authentication_classes = [JwtQueryParamsAuthentication, ]

    filter_class = UserFilter
